package com.tidy.seed.interceptor;

import com.tidy.seed.annotation.ApiPermission;
import com.tidy.seed.annotation.NoToken;
import com.tidy.seed.common.StatusCode;
import com.tidy.seed.exception.BaseException;
import com.tidy.seed.admin.system.service.RoleApiService;
import com.tidy.seed.admin.system.service.UserRoleService;
import com.tidy.seed.admin.system.vo.UserApiPermissionVO;
import com.tidy.seed.util.HttpUtils;
import com.tidy.seed.util.ObjUtils;
import com.tidy.seed.util.UserThreadLocal;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class PermissionInterceptor implements HandlerInterceptor {
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleApiService roleApiService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("------------PermissionInterceptor执行-----------------");
        // 不是 controller 方法直接放行
        if (!(handler instanceof HandlerMethod)) return true;
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        String httpMethod = request.getMethod();  // 获取请求方式(GET、POST等)
        String path = request.getRequestURI();
        String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        Class<?> controllerClass = method.getDeclaringClass();

        // 如果方法或类上有 @NoToken → 直接放行
        if (AnnotatedElementUtils.hasAnnotation(hm.getMethod(), NoToken.class)
                || AnnotatedElementUtils.hasAnnotation(hm.getBeanType(), NoToken.class)) return true;

        // 如果方法或类上都没有 @ApiPermission → 放行
        if (!AnnotatedElementUtils.hasAnnotation(hm.getMethod(), ApiPermission.class)
                && !AnnotatedElementUtils.hasAnnotation(hm.getBeanType(), ApiPermission.class)) return true;
        System.out.println("请求方式: " + httpMethod);
        System.out.println("请求匹配的路径模板：" + pattern);
        System.out.println("当前请求接口路径：" + path);
        System.out.println("当前请求接口方法：" + method);
        Integer userId = UserThreadLocal.getUserId();
        System.out.println("userId：" + userId);
        if (ObjUtils.isNotNull(userId)) {
            //Integer[] roleIds = userRoleService.findRoleIdsByUserId(userId);
            //UserThreadLocal.putRoleIds(roleIds);
            //获取到接口权限菜单 [UserApiPermissionVO(apiId=15, roleId=1, apiUrl=/user, method=2),...]
            List<UserApiPermissionVO> userApiPermission = roleApiService.getRoleIdsAndApisByUserId(userId);
            //有该接口权限通过检查
            boolean isPassCheck =
                    userApiPermission.stream().anyMatch(item -> HttpUtils.getMethod(item.getMethod()).equals(httpMethod) && Objects.equals(item.getApiUrl(), path));
            //System.err.println(isPassCheck);
            if (!isPassCheck)
                throw new BaseException(StatusCode.CODE_401, "用户:" + UserThreadLocal.getUsername() + "无" + path + "接口权限");
        }


        return true;
    }
}
